<?php

namespace App\Http\Admin\Services\Order;

use App\Exceptions\InvalidRequestException;

use App\Http\Models\Fans;
use App\Http\Models\FansPhones;
use App\Http\Models\TaobaoOrders;
use App\Http\Services\BaseOrderService;
use App\Lib\PHPExcel\ExcelHandle;
use Illuminate\Support\Facades\DB;


class TaobaoOrderService extends BaseOrderService
{
    public function list($conditions = []){

        $query = TaobaoOrders::query();

        if(!empty($conditions['order_id'])){
            $query  =   $query->where('order_id','like',"%".$conditions['order_id']."%");
        }
        if(!empty($conditions['phone'])){
            $query  =   $query->where('post_tel','like',"%".$conditions['phone']."%");
        }
        if(!empty($conditions['liver'])){
            $query  =   $query->where('liver','like',"%".$conditions['liver']."%");
        }
        if(!empty($conditions['post_recevier'])){
            $query  =   $query->where('post_recevier','like',"%".$conditions['post_recevier']."%");
        }
        if(!empty($conditions['shop_name'])){
            $query  =   $query->where('shop_name','like',"%".$conditions['shop_name']."%");
        }
        if(!empty($conditions['start_time']) && !empty($conditions['end_time'])){
            $query  =   $query->whereBetween('create_time',[$conditions['start_time'],$conditions['end_time']]);
        }
        $query_sum = clone ($query);
        $list = $query->orderBy('create_time','desc')->paginate(50);

        $list = $this->filter($list);

        //算综合
        $raw = DB::raw('sum(total_amount) as total_amount,sum(payment_integral) as payment_integral,sum(actual_payment_amount) as actual_payment_amount,sum(actual_payment_integral) as actual_payment_integral');
        $data = $query_sum->select($raw)->first();
        return [
            'list' =>  $list,
            'data' =>  $data
        ];
    }


    public function filter($arr){
        if (count($arr) > 0) {
            $phones = $arr->pluck('post_tel');

            $fans = FansPhones::select('fans.nickname','fans_phones.phone')->LeftJoin('fans','fans.unique_id','fans_phones.fans_id')->whereIn('fans_phones.phone',$phones)->get()->toArray();

           // $orders =   TaobaoOrders::whereNotIn('order_status',['交易关闭','等待买家付款'])->whereIn('post_tel',$phones)->get()->toArray();


            foreach ($arr as $key => $item) {

                //昵称
                $item['nickname'] = collect($fans)->where('phone', $item['post_tel'])->first()['nickname'] ?? '未知';
                $item['actual_payment_amount'] = round($item['actual_payment_amount'],2);

                //$total  =   collect($orders)->where('post_tel',$item['post_tel'])->sortByDesc('create_time')->values()->all();
                //$item['lastBuyTime']    =   $total[0]['create_time'] ?? '';
               // $item['firstBuyTime']   =   $total[count($total)-1]['create_time'] ?? '';
                $arr[$key]  =   $item;
            }

        }

        return $arr;
    }

    public function import($conditions  =   []){
        set_time_limit(0);
        $arr = ExcelHandle::read1();
        $liver  =   $conditions['liver'];
        if (count($arr) == 0 || empty($liver)) {
            throw new InvalidRequestException('数据不能为空');
        }
        $i = 0;
        foreach ($arr as $item){
            if(!empty($item['A'])){
                $order_id = $item['A'];
                $it = [
                    'order_id' => $item['A'],
                    'buyer_nickname' => $item['B'],
                    'buyer_zfb' => $item['C'],
                    'payment_code' => $item['D'],
                    'payment_detail' => !empty($item['E']) ? $item['E'] : '',
                    'payment_amount' => !empty($item['F']) ? $item['F'] : 0,
                    'feight_payment_amount' => !empty($item['G']) ? $item['G'] : 0,
                    'payment_integral' => !empty($item['H']) ? $item['H'] : 0,
                    'total_amount' => !empty($item['I']) ? $item['I'] : 0,
                    'return_integral' => !empty($item['J']) ? $item['J'] : 0,
                    'actual_payment_amount' => !empty($item['K']) ? $item['K'] : 0,
                    'actual_payment_integral' => !empty($item['L']) ? $item['L'] : 0,
                    'order_status' => $item['M'],
                    'buyer_words' => !empty($item['N']) && $item['N'] != "null" ? $item['N'] : '',
                    'post_recevier' => $item['O'],
                    'post_address' => !empty($item['P']) ? $item['P'] : '',
                    'delivery_mode' => $item['Q'],
                    'post_tel' =>  ltrim($item['S'], "'"),
                    'create_time' => !empty($item['T']) ? $item['T'] :  null,
                    'payment_time' => !empty($item['U']) ? $item['U'] : null,
                    'prod_name' => $item['V'],
                    'prod_type' => $item['W'],
                    'logistics_code' => !empty($item['X']) ? $item['X'] : '',
                    'logistics_comp' => !empty($item['Y']) && $item['Y'] != 'null' ? $item['Y'] : '',
                    'remark' => !empty($item['Z']) && $item['Z'] != "'null" ? ltrim($item['Z'], "'") : '',
                    'prod_total_amount' => $item['AA'],
                    'shop_name' => !empty($item['AC']) ? $item['AC'] : '',
                    'cancel_reason' => !empty($item['AD']) ? $item['AD'] : '',
                    'order_type' => !empty($item['AH']) ? $item['AH'] : '',
                    'modify_address' => !empty($item['AP']) && $item['AP'] != "null" ? $item['AP'] : '',
                    'liver'=>$liver,
                    'date'=>!empty($item['U']) ? $item['U'] : null,
                ];

                $flag = TaobaoOrders::where('order_id',$order_id)->exists();
                if($flag){
                    TaobaoOrders::where('order_id',$order_id)->update($it);
                }else{
                    TaobaoOrders::create($it);
                }
                $i++;
            }
        }
        return $i;
    }


    public function export($conditions = []){
        $query = TaobaoOrders::query();
        if(!empty($conditions['order_id'])){
            $query  =   $query->where('order_id','like',"%".$conditions['order_id']."%");
        }
        if(!empty($conditions['phone'])){
            $query  =   $query->where('post_tel','like',"%".$conditions['phone']."%");
        }
        if(!empty($conditions['post_recevier'])){
            $query  =   $query->where('post_recevier','like',"%".$conditions['post_recevier']."%");
        }
        if(!empty($conditions['shop_name'])){
            $query  =   $query->where('shop_name','like',"%".$conditions['shop_name']."%");
        }
        if(!empty($conditions['start_time']) && !empty($conditions['end_time'])){
            $query  =   $query->whereBetween('create_time',[$conditions['start_time'],$conditions['end_time']]);
        }

        $list = $query->orderBy('create_time','desc')->get();

        $list   =   $this->filter($list);

        $title = '淘宝订单';

        ExcelHandle::factory('TaobaoOrder', $title, $list)->export();
    }


    /*
     * 用户订单信息统计
     * */

    public function buyerList($conditions   =   []){

        $modal  =   TaobaoOrders::select([
            DB::raw('sum(actual_payment_amount) as actual_payment_amount'),
            DB::raw('count(1) as number'),
            DB::raw('max(create_time) as last_time'),
            DB::raw('min(create_time) as first_time'),
            'post_recevier',
            DB::raw('max(post_address) as post_address'),
            'post_tel',
            ]);

        $modal  =   $modal->leftJoin(DB::raw('fans_phones'),'fans_phones.phone','admin_taobao_orders.post_tel')->leftJoin(DB::raw('fans'),'fans_phones.fans_id','fans.unique_id');

        if(!empty($conditions['post_recevier'])){
            $modal = $modal->where('post_recevier',$conditions['post_recevier']);
        }
        if(!empty($conditions['post_tel'])){
            $modal = $modal->where('post_tel',$conditions['post_tel']);
        }
        if(!empty($conditions['liver'])){
            $modal = $modal->where('liver',$conditions['liver']);
        }
        if(!empty($conditions['post_address'])){
            $modal = $modal->where('post_address',"like","%".$conditions['post_address']."%");
        }
        if(!empty($conditions['nickname'])){
            if($conditions['nickname'] == 1){
                $modal = $modal->whereNotNull('nickname');
            }else{
                $modal = $modal->whereNull('nickname');
            }

        }

        $list = $modal->whereNotIn('order_status',['交易关闭','等待买家付款'])->whereNotNull('post_recevier');

        if(!empty($conditions['order'])){
            $list   =   $list->orderBy($conditions['key'],$conditions['order']);
        }
        $list   =   $list->groupBy('post_recevier','post_tel')->paginate(50);

        $list = $this->filter($list);

        return $list;

    }

    /*
     * 用户数据导出
     * */
    public function buyerExport($conditions = []){
        $modal  =   TaobaoOrders::select([
            DB::raw('sum(actual_payment_amount) as actual_payment_amount'),
            DB::raw('count(1) as number'),
            DB::raw('max(create_time) as last_time'),
            DB::raw('min(create_time) as first_time'),
            'post_recevier',
            DB::raw('max(post_address) as post_address'),
            'post_tel',
            ]);

        $modal  =   $modal->leftJoin(DB::raw('fans_phones'),'fans_phones.phone','admin_taobao_orders.post_tel')->leftJoin(DB::raw('fans'),'fans_phones.fans_id','fans.unique_id');

        if(!empty($conditions['post_recevier'])){
            $modal = $modal->where('post_recevier',$conditions['post_recevier']);
        }
        if(!empty($conditions['post_tel'])){
            $modal = $modal->where('post_tel',$conditions['post_tel']);
        }
        if(!empty($conditions['liver'])){
            $modal = $modal->where('liver',$conditions['liver']);
        }
        if(!empty($conditions['post_address'])){
            $modal = $modal->where('post_address',"like","%".$conditions['post_address']."%");
        }
        if(!empty($conditions['nickname'])){
            if($conditions['nickname'] == 1){
                $modal = $modal->whereNotNull('nickname');
            }else{
                $modal = $modal->whereNull('nickname');
            }

        }
        $list = $modal->whereNotIn('order_status',['交易关闭','等待买家付款'])->whereNotNull('post_recevier')->groupBy('post_recevier','post_tel')->get()->toArray();

        $list   =   collect($list)->values()->all();
        $tmp    =   [];
        $page   =   round(count($list)/100);
        for ($i = 1;$i<=$page;$i++){
            $data   =   collect($list)->forPage($i,100);
            $perPage = $this->filter($data);
            foreach ($perPage as $item){
                array_push($tmp,$item);
            }
        }

        $title = '淘宝订单用户数据';

        ExcelHandle::factory('TaobaoOrderUsers', $title, $tmp)->export();
    }

    /*
     * 粉丝备注
     * */
    public function storeMark($data = []){

        if(!empty($data)){

            $unique_id  =   '888'.strtotime(date("Y-m-d H:i:s"));

            $is_exists  =   FansPhones::where('phone',$data['phone'])->exists();

            $int_fans           =   [];
            $int_fans_phone     =   [];
            if(!$is_exists){
                $int_fans['nickname']   =   $data['nickname'];
                $int_fans['unique_id']      =   $int_fans_phone['fans_id'] =   $unique_id;
                $int_fans_phone['phone']   =   $data['phone'];
                FansPhones::insert($int_fans_phone);
                Fans::insert($int_fans);

            }else{
                $phone =   FansPhones::where('phone',$data['phone'])->first();
                Fans::where('unique_id',$phone->fans_id)->update(['nickname'=>$data['nickname']]);
            }

        }
        return res('备注完成',$data);

    }


    /*
     * 主播日成交额
     * */
    public function liverBusiness($conditions   =   []){

        $data   =   TaobaoOrders::select([
            DB::raw('sum(actual_payment_amount) as actual_payment_amount'),
            DB::raw('count(1) as order_count'),
            'liver',
            'date'
        ])->whereNotIn('order_status',['交易关闭','等待买家付款'])->whereNotNull('date');

        if(!empty($conditions['start_time']) && !empty($conditions['end_time'])){
            $data   =   $data->whereBetween('date',[$conditions['start_time'],$conditions['end_time']]);
        }
        if(!empty($conditions['liver'])){
            $data   =   $data->where('liver',$conditions['liver']);
        }
        if(!empty($conditions['order'])){
            $data   =   $data->orderBy($conditions['key'],$conditions['order']);
        }

        $data   =   $data->orderBy('date','desc')->groupby('liver','date')->paginate(50);

        foreach ($data as $k => $v){
            $total =  TaobaoOrders::select(DB::raw('count(1) as person'))->whereNotIn('order_status',['交易关闭','等待买家付款'])->where('liver',$v['liver'])->where('date',$v['date'])->groupBy('post_tel')->get();
            $v['user_count']                =   count($total);
            $v['actual_payment_amount']     =   round($v['actual_payment_amount'],2);
            $data[$k]   =   $v;
        }

        return $data;

    }

    /*
     * 主播日成交额  导出
     * */

    public function liverExport($conditions =   []){
        $data   =   TaobaoOrders::select([
            DB::raw('sum(actual_payment_amount) as actual_payment_amount'),
            DB::raw('count(1) as order_count'),
            'liver',
            'date'
        ])->whereNotIn('order_status',['交易关闭','等待买家付款'])->whereNotNull('date');

        if(!empty($conditions['liver'])){
            $data   =   $data->where('liver',$conditions['liver']);
        }

        $data   =   $data->orderBy('date','desc')->groupby('liver','date')->get(50);

        foreach ($data as $k => $v){
            $total =  TaobaoOrders::select(DB::raw('count(1) as person'))->whereNotIn('order_status',['交易关闭','等待买家付款'])->where('liver',$v['liver'])->where('date',$v['date'])->groupBy('post_tel')->get();
            $v['user_count']                =   count($total);
            $v['actual_payment_amount']     =   round($v['actual_payment_amount'],2);
            $data[$k]   =   $v;
        }

        return $data;
    }

}